import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form';
import { FormattedMessage, injectIntl } from 'react-intl';

import {
  TextField,
  Select,
  Button,
  Col,
  Row,
} from '@folio/stripes/components';

function asyncValidate(values, dispatch, props, blurredField) {
  const {
    httpValidatorInvoke,
    initialValues

  } = props;

  if (values[blurredField]) {
    values[blurredField] = values[blurredField].trim();
  }

  const curValue = values[blurredField];

  if (!!initialValues && initialValues.id) {
    const prevValue = initialValues[blurredField];
    if (curValue !== prevValue) {
      return asyncValidateField(blurredField, curValue, httpValidatorInvoke);
    } else {
      return new Promise((resolve, reject) => {
        return resolve();
      });
    }
  } else if (blurredField) {
    const promises = [];

    promises.push(asyncValidateField(blurredField, values[blurredField], httpValidatorInvoke));
    return Promise.all(promises);
  } else {
    return Promise.all([]);
  }
}

function asyncValidateField(field, value, validator) {
  return new Promise((resolve, reject) => {
    const query = {

    };
    query[field] = value;
    let queryParams = ''
    if (query['name']){
        queryParams = `(isDel = 0 and name = ${query['name']})`
    }
    if (query['code']){
        queryParams = `(isDel = 0 and code = ${query['code']})`
    }
    validator.reset();
    return validator.GET({ params: { query: queryParams } })
      .then(result => {
        if (result.partySetGroup.length > 0) {
          const error = {};
          error[field] = (
              <FormattedMessage id={"ui-party.other.already.exists"}></FormattedMessage>
            // <FormattedMessage id="ui-party.messageTemplate.data.name.error"/>
          );
          return reject(error);
        } else {
          return resolve();
        }
      });
  });
}

function validate(values, props) {
  const errors = {};

  if (!values || !values.name) {
    errors.name = (<FormattedMessage id="ui-party.errors.missingRequiredField" />);
  }
  if (!values || !values.code) {
    errors.code = (<FormattedMessage id="ui-party.errors.missingRequiredField" />);
  }
  if (!values || !values.content) {
    errors.content = (<FormattedMessage id="ui-party.errors.missingRequiredField" />);
  }
  if (!values || !values.state) {
    errors.state = (<FormattedMessage id="ui-party.errors.missingRequiredField" />);
  }
  return errors;
}

class EditForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: true,
      title: '添加配置',
      show: false,
      editsStatus: 'success',
      message: '保存成功'
    };
  }

    static propTypes = {
      handleSubmit: PropTypes.func.isRequired,
      initialValues: PropTypes.object,
      dictionary: PropTypes.object,
      cleanSearch: PropTypes.func,
      intl: PropTypes.func
    };

    render() {
 
      const footer = (
        <React.Fragment>
          <div>

            <Button onClick={this.props.cancel}>
              <FormattedMessage id="ui-party.cancel" />
            </Button>
            <Button
              buttonStyle="primary"
              marginBottom0
              type="submit"
            >
              <FormattedMessage id="ui-party.saveAndExit" />
            </Button>
          </div>
        </React.Fragment>
      );
      const {
        handleSubmit,

        intl
      } = this.props;

      return (

        <Row center="xs" style={{ width: '100%' }}>
          <Col xs={6}>
            <form data-test-form-page id="form-add" onSubmit={handleSubmit}>

              <Field
                component={TextField}
                name="name"

                label={<FormattedMessage id="ui-party.loans.columns.party.sys.settingName" />}
                required
              />
              <Field
                component={TextField}
                name="code"

                label={<FormattedMessage id="ui-party.loans.columns.party.sys.code" />}
                required
              />
              <Field
                component={TextField}
                name="content"

                label={<FormattedMessage id="ui-party.loans.columns.party.sys.content" />}
                required
              />

              <Field
                required
                component={Select}
                name="state"

                label={
                  <FormattedMessage id="ui-party.loans.columns.party.sys.state" />
                            }
                dataOptions={[
                    {   id: '0',
                        label: intl.formatMessage({ id: 'ui-party.please.select' }) ,
                        value: ''
                    },
                  {
                      id: '1',
                    label:  intl.formatMessage({ id: 'ui-party.messageTemplate.data.state.enable' })  ,
                    value: 1
                  },
                  {
                      id: '2',
                    label:  intl.formatMessage({ id: 'ui-party.messageTemplate.data.state.disable' }) ,
                    value: 0
                  }
                ]}
              />
              {footer}


            </form>
          </Col>
        </Row>

      );
    }
}

export default injectIntl(
  reduxForm({
    form: 'SystemSettingEditForm',
    validate,
    asyncValidate,
    asyncBlurFields: ['name', 'code'],
    navigationCheck: true,
    enableReinitialize: true
  })(EditForm)
);
